import React from "react";
import { css } from "@emotion/css";
import { makeDecoratable } from "@webiny/app-admin";
import { Menu, MenuItem } from "@webiny/ui/Menu/index.js";
import { ReactComponent as MoreVerticalIcon } from "@webiny/icons/more_vert.svg";
import { ListItemGraphic } from "@webiny/ui/List/index.js";
import { Icon } from "@webiny/ui/Icon/index.js";
import { IconButton } from "@webiny/admin-ui";

const menuStyles = css`
    .disabled {
        opacity: 0.5;
        pointer-events: none;
    }
`;

export interface OptionsMenuItem {
    label: string;
    icon: React.ReactElement;
    onClick: () => void;
    disabled?: boolean;
    "data-testid"?: string;
}

export interface OptionsMenuProps {
    items: OptionsMenuItem[];
    "data-testid"?: string;
}

export const OptionsMenu = makeDecoratable(
    "CmsModelsOptionsMenu",
    ({ items, ...props }: OptionsMenuProps) => {
        if (!items.length) {
            return null;
        }

        return (
            <Menu
                className={menuStyles}
                handle={<IconButton icon={<MoreVerticalIcon />} size={"sm"} variant={"ghost"} />}
                anchor={"topLeft"}
                {...props}
            >
                {items.map(item => (
                    <MenuItem
                        key={item.label}
                        disabled={item.disabled ?? false}
                        onClick={item.onClick}
                        data-testid={item["data-testid"]}
                    >
                        <ListItemGraphic>
                            <Icon icon={item.icon} />
                        </ListItemGraphic>
                        {item.label}
                    </MenuItem>
                ))}
            </Menu>
        );
    }
);
